<template>
  <div class=''>

    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card class="box-card">
        <!-- 警告区域 -->
        <el-alert
          title="注意：只允许为第三级分类设置参数"
          type="warning"
          show-icon
          :closable="true">
        </el-alert>

        <!-- 选择商品分类区域 -->
        <el-row class="cat_opt">
          <el-col>
              <span>选择商品分类：</span>
              <!-- 选择商品分类的级联选择框 -->
              <el-cascader
              :options="cateList"
              :props="cascaderProps"
              @change="cateSelectedChange"
              :show-all-levels="false"
              clearable
            ></el-cascader>
          </el-col>
        </el-row>

        <!-- tab 页区域 -->
        <el-tabs v-model="activeName" @tab-click="tabClick">

          <!-- 添加动态参数面板 -->
          <el-tab-pane label="动态参数" name="many">

            <!-- 添加参数按钮 -->
            <el-button
            type="primary" size="mini" :disabled="isBtnDisabled"
            @click="addAttrDialogShow">添加参数</el-button>

            <!-- 动态参数表格 -->
            <el-table :data="manyAttrList" border stripe>
              <!-- 展开列 -->
              <el-table-column type="expand">
                 <template slot-scope="scope">
                    <el-tag
                    v-for="(v, i) in scope.row.attr_vals" :key="i"
                    closable @close="tagColsed(scope.row, i)"
                    >{{v}}</el-tag>
                    <!-- 输入文本框 -->
                    <el-input
                      class="input-new-tag"
                      v-if="scope.row.inputVisible"
                      v-model="scope.row.inputValue"
                      ref="saveTagInput"
                      size="small"
                      @keyup.enter.native="enterUp"
                      @blur="handleInputConfirm(scope.row)"
                    >
                    </el-input>
                    <!-- 按钮框 -->
                    <el-button
                    v-else class="button-new-tag" size="small"
                    @click="showInput(scope.row)"
                    >+ New Tag</el-button>
                 </template>
              </el-table-column>
              <!-- 索引列 -->
              <el-table-column type="index" label="#"/>
              <el-table-column label="参数名称" prop="attr_name" />
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <!-- 修改参数按钮 -->
                  <el-button
                    type="primary" icon="el-icon-edit" size="mini"
                    @click="editAttrDialogShow(scope.row.attr_id)"
                  >编辑</el-button>

                  <!-- 删除参数按钮 -->
                  <el-button
                    type="danger" icon="el-icon-delete" size="mini"
                    @click="removeArrtById(scope.row.attr_id)"
                  >删除</el-button>

                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>

          <!-- 添加静态属性面板 -->
          <el-tab-pane label="静态属性" name="only">

            <!-- 添加属性按钮 -->
            <el-button
            type="primary" size="mini" :disabled="isBtnDisabled"
            @click="addAttrDialogShow"
            >添加属性</el-button>

            <!-- 静态参数表格 -->
            <el-table :data="onlyAttrList" border stripe>
              <!-- 展开列 -->
              <el-table-column type="expand">
                 <template slot-scope="scope">
                    <el-tag
                    v-for="(v, i) in scope.row.attr_vals" :key="i"
                    closable @close="tagColsed(scope.row, i)"
                    >{{v}}</el-tag>
                    <!-- 输入文本框 -->
                    <el-input
                      class="input-new-tag"
                      v-if="scope.row.inputVisible"
                      v-model="scope.row.inputValue"
                      ref="saveTagInput"
                      size="small"
                      @keyup.enter.native="enterUp"
                      @blur="handleInputConfirm(scope.row)"
                    >
                    </el-input>
                    <!-- 按钮框 -->
                    <el-button
                    v-else class="button-new-tag" size="small"
                    @click="showInput(scope.row)"
                    >+ New Tag</el-button>
                 </template>
              </el-table-column>
              <!-- 索引列 -->
              <el-table-column type="index" label="#"/>
              <el-table-column label="参数名称" prop="attr_name" />
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <!-- 修改参数按钮 -->
                  <el-button
                    type="primary" icon="el-icon-edit" size="mini"
                    @click="editAttrDialogShow(scope.row.attr_id)"
                  >编辑</el-button>

                  <!-- 删除参数按钮 -->
                  <el-button
                    type="danger" icon="el-icon-delete" size="mini"
                    @click="removeArrtById(scope.row.attr_id)"
                  >删除</el-button>

                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
    </el-card>

    <!-- 添加参数的对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addAttrDialogVisible"
      width="50%"
      @close="addAttrDialogClosed"
      >

      <!-- 内容主体区域 -->
      <el-form
        :model="addAttrFrom"
        :rules="addAttrFromRules"
        label-width="100px"
        ref="addAttrFromRef"
      >
        <el-form-item label="参数名称:" prop="attr_name">
          <el-input v-model="addAttrFrom.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addAttrDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addAttr">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改参数的对话框 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editAttrDialogVisible"
      width="50%"
      @close="editAttrDialogClosed"
      >

      <!-- 内容主体区域 -->
      <el-form
        :model="editAttrFrom"
        :rules="editAttrFromRules"
        label-width="100px"
        ref="editAttrFromRef"
      >
        <el-form-item label="参数名称:" prop="attr_name">
          <el-input v-model="editAttrFrom.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editAttrDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editAttr">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>

export default {
  name: 'Params',
  props: {

  },
  data () {
    return {
      cateList: [],
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      pidId: null,
      activeName: 'many',
      isBtnDisabled: true,
      manyAttrList: [],
      onlyAttrList: [],
      // 与添加参数有关的数据
      addAttrDialogVisible: false,
      addAttrFrom: {
        attr_name: ''
      },
      addAttrFromRules: {
        attr_name: [
          { required: true, message: '请输入参数', trigger: 'blur' }
        ]
      },
      // 与修改参数有关数据
      editAttrDialogVisible: false,
      editAttrFrom: {},
      editAttrFromRules: {
        attr_name: [
          { required: true, message: '请输入参数', trigger: 'blur' }
        ]
      },
      // 与添加tag有关数据
      inputVisible: false,
      inputValue: ''
    }
  },
  created () {
    this.getCateList()
  },
  computed: {
    titleText () {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  },
  methods: {
    // 获取商品列表
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品列表失败')
      }
      this.cateList = res.data
    },

    // 获取参数列表
    async getAttrList () {
      // 获取参数列表
      const { data: res } = await this.$http.get(
        `categories/${this.pidId}/attributes`, {
          params: { sel: this.activeName }
        }
      )
      if (res.meta.status !== 200) {
        this.$message.error('获取参数列表失败')
        return
      }
      res.data.forEach(v => {
        v.attr_vals = v.attr_vals ? v.attr_vals.split(' ') : []
        v.inputVisible = false
        v.inputValue = ''
      })
      if (this.activeName === 'many') {
        this.manyAttrList = res.data
      } else {
        this.onlyAttrList = res.data
      }
    },
    // 监听 选择框值改变事件
    cateSelectedChange (arr) {
      // 判断是否有选中父级
      if (arr.length === 0) {
        this.pidId = null
        this.isBtnDisabled = true
        this.manyAttrList = []
        this.onlyAttrList = []
      } else {
        this.pidId = arr[arr.length - 1]
        this.isBtnDisabled = false
        // 发起 获取参数列表请求
        this.getAttrList()
      }
    },

    // tab 的点击事件
    tabClick (v) {
      if (!this.pidId) return
      this.getAttrList()
    },

    // 展示 添加参数对话框
    addAttrDialogShow () {
      this.addAttrDialogVisible = true
    },

    // 监听 添加参数对话框的关闭
    addAttrDialogClosed () {
      this.$refs.addAttrFromRef.resetFields()
    },

    // 执行添加参数
    addAttr () {
      this.$refs.addAttrFromRef.validate(async valid => {
        if (!valid) return

        // 发起添加用户请求
        const { data: res } = await this.$http.post(
          `categories/${this.pidId}/attributes`, {
            attr_name: this.addAttrFrom.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 201) return this.$message.error('参数添加失败')
        this.$message.success('参数添加成功')

        // 更新数据
        this.getAttrList()
        // 关闭添加参赛对话框
        this.addAttrDialogVisible = false
      })
    },

    // 展示 修改参数对话框
    async editAttrDialogShow (id) {
      // 根据参数id 获取参数信息
      const { data: res } = await this.$http.get(
        `categories/${this.pidId}/attributes/${id}`, {
          attr_sel: this.activeName
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.editAttrFrom = res.data
      this.editAttrDialogVisible = true
    },

    // 监听 修改参数对话框的关闭
    editAttrDialogClosed () {
      this.$refs.editAttrFromRef.resetFields()
    },

    // 执行修改参数
    editAttr () {
      this.$refs.editAttrFromRef.validate(async valid => {
        if (!valid) return

        // 发起修改请求
        const { data: res } = await this.$http.put(
          `categories/${this.pidId}/attributes/${this.editAttrFrom.attr_id}`, {
            attr_name: this.editAttrFrom.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 200) return this.$message.error('参数修改失败')
        this.$message.success('参数修改成功')

        // 更新数据
        this.getAttrList()
        // 关闭添加参赛对话框
        this.editAttrDialogVisible = false
      })
    },

    // 执行删除参数
    async removeArrtById (id) {
      const confirmResult = await this.$confirm('此操作将永久删除该参数', '提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning'
      }).catch(err => {
        return err
      })

      // 判断是否发起删除角色请求
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }

      // 发起删除角色请求
      const { data: res } = await this.$http.delete(
        `categories/${this.pidId}/attributes/${id}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除参数失败')
      }
      this.$message.success('删除参数成功')

      // 重新获取参数列表
      this.getAttrList()
    },

    // 关闭tag
    async tagColsed (role, i) {
      role.attr_vals.splice(i, 1)

      // 发起修改请求
      const { data: res } = await this.$http.put(
        `categories/${this.pidId}/attributes/${role.attr_id}`, {
          attr_name: role.attr_name,
          attr_sel: role.attr_sel,
          attr_vals: role.attr_vals.join(' ')
        }
      )
      if (res.meta.status !== 200) return this.$message.error('参数修改失败')
      this.$message.success('参数修改成功')
    },
    showInput (role) {
      role.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    enterUp () {
      this.$refs.saveTagInput.$refs.input.blur()
    },
    async handleInputConfirm (role) {
      if (role.inputValue) {
        role.attr_vals.push(role.inputValue.trim())
      }
      role.inputVisible = false
      role.inputValue = ''
      // 发起修改请求
      const { data: res } = await this.$http.put(
        `categories/${this.pidId}/attributes/${role.attr_id}`, {
          attr_name: role.attr_name,
          attr_sel: role.attr_sel,
          attr_vals: role.attr_vals.join(' ')
        }
      )
      if (res.meta.status !== 200) return this.$message.error('参数修改失败')
      this.$message.success('参数修改成功')
    }
  }
}
</script>
<style scoped>
.el-breadcrumb{
  margin-bottom: 15px;
  font-size: 12px;
}
.box-card{
  box-shadow:  0 1px 1px rgba(0, 0, 0, 0.15) !important;
}
.cat_opt{
  margin: 10px 0;
}
.cat_opt span{
    text-align: right;
    vertical-align: middle;
    float: left;
    font-size: 14px;
    color: #606266;
    line-height: 40px;
    padding: 0 16px;
}
.el-table{
  margin-top: 15px;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
